#include"sort.h"
void swap(int* x, int* y) {
	int tmp = *x;
	*x = *y;
	*y = tmp;
}
void AdJustDown(int* arr, int parent,int size) {
	int child = parent * 2 + 1;
	while (child < size) {
		if (child < size-1 && arr[child]>arr[child + 1]) {
			child++;
		}
		if (arr[parent] > arr[child]) {
			swap(&arr[parent], &arr[child]);
			parent = child;
			child = parent * 2 + 1;
		}
		else {
			break;
		}
	}
}
void HeapSort(int* arr,int size) {
	
	for (int i = (size - 1 - 1) / 2; i >= 0; i--) {
		AdJustDown(arr, i, size);
	}
	int end = size - 1;
	while (end) {
		swap(&arr[0], &arr[end]);
		AdJustDown(arr, 0, end);
		end--;
	}
}
void ArrPrint(int* arr,int size) {
	for (int i = 0; i < size; i++) {
		printf("%d ", arr[i]);
	}
	printf("\n");
}
void bubbleSort(int* arr,int size) {
	int exchage = 0;
	for (int i = 0; i < size-1; i++) {
		for (int j = i; j < size - i - 1; j++) {
			if (arr[j] > arr[j + 1]) {
				swap(&arr[j], &arr[j + 1]);
				exchage = 1;
			}
		}
		if (exchage == 0) {
			break;
		}
	}
}

void insertSort(int* arr, int size) {
	for (int i = 0; i < size - 1; i++) {
		int end = i;
		int tmp = arr[i + 1];
		while (end>=0) {
			if (arr[end] > tmp) {
				arr[end+1] = arr[end];
				end--;
			}
			else {
				break;
			}
		}
		arr[end + 1] = tmp;
	}
}

void shellSort(int* arr, int size) {
	int gap = size;
	while (gap > 1) {
		gap = gap / 3 + 1;
		for (int i = 0; i < size - gap; i++) {
			int end = i;
			int tmp = arr[end + gap];
			while (end >= 0) {
				if (arr[end] > tmp) {
					arr[end + gap] = arr[end];
					end -= gap;
				}
				else {
					break;
				}
			}
			arr[end + gap] = tmp;
		}
	}
}
void selectSort(int* arr, int size) {
	int begin = 0;
	int end = size - 1;
	while (begin < end) {
		int maxi = begin;
		int mini = begin;
		for (int i = begin + 1; i <= end; i++) {
			if (arr[i] > arr[maxi]) {
				maxi = i;
			}
			if (arr[i] < arr[mini]) {
				mini = i;
			}
		}
		if (maxi == begin) {
			maxi = mini;
		}
		swap(&arr[begin], &arr[mini]);
		swap(&arr[end], &arr[maxi]);
		++begin;
		--end;
	}
}